package logic

import (
	"box-ma-fresh/boxrpc/boxrpc"
	"box-ma-fresh/boxrpc/internal/svc"
	"box-ma-fresh/mysql/model"
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建商品
func (l *GoodsAddLogic) GoodsAdd(in *boxrpc.GoodsAddRequest) (*boxrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	boxGoods := &model.BoxGoods{
		Tid:     in.Tid,
		Title:   in.Title,
		Price:   float64(in.Price),
		Content: in.Content,
	}
	tx := model.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	err := boxGoods.BoxGoodsDetail(model.DB, in.Title)
	if err == nil {
		return nil, errors.New("商品的名称重复")
	}
	err = boxGoods.BoxGoodsAdd(model.DB)
	if err != nil {
		return nil, err
	}
	err = tx.Commit().Error
	if err != nil {
		return nil, err
	}
	return &boxrpc.GoodsAddResponse{
		GoodId: int64(boxGoods.ID),
	}, nil
}
